package com.mp.tanlong;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.net.http.SslError;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.provider.AlarmClock;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.mp.tanlong.DownLoadThread.DownloadProgressListener;
import com.mp.tanlong.WpsModel.ClassName;
import com.mp.tanlong.WpsModel.OpenMode;
import com.mp.tanlong.WpsModel.PackageName;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@SuppressWarnings("deprecation")
@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public class MainActivity extends Activity implements DownloadProgressListener{
	private long mkeyTime = 0;

    public static final int FLAG_SECURE             = 0x00002000;
    public static final int FLAG_KEEP_SCREEN_ON     = 0x00000080;

    private static final String APP_CACAHE_DIRNAME = "/webcache";
    public static final int MIXED_CONTENT_ALWAYS_ALLOW = 0;
    public static final int RESULT_CANCELED = 0;
    public static final int RESULT_OK = -1;
    public static final int RESULT_FIRST_USER = 1;
	@SuppressWarnings("unused")
	private static final int FILE_SELECT_CODE = 1;
	public static final int RC_CHOOSE_PHOTO = 2;


    private CookieManager mCookieManager;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

	public static final String EXTRA_ALLOW_MULTIPLE ="android.intent.extra.ALLOW_MULTIPLE";


    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private ProgressBar progressBar;
    WebView webview;
	@SuppressWarnings({ "static-access" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Intent intent=new Intent(this,GrayService.class);
       // getApplicationContext().startService(intent);
		setContentView(R.layout.activity_main);
		   //获取sharedPreferences对象
        //sharedPreferences = getSharedPreferences("myshare", Context.MODE_PRIVATE);
        //获取editor对象
        //获取编辑器
       // editor = sharedPreferences.edit();
		//Android中禁用锁屏界面2
		//KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
		//KeyguardManager.KeyguardLock kl = km.newKeyguardLock("name");
		//kl.disableKeyguard();

		AndroidBug5497Workaround.assistActivity(this);
		final Window win = getWindow();
		   win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
	                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
	                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
	                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		//getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);



		progressBar= findViewById(R.id.progressbar);//进度条
		webview = findViewById(R.id.webView1);

		WebSettings webSettings = webview.getSettings();
		webSettings.setDefaultTextEncodingName("utf-8");
		webSettings.setJavaScriptEnabled(true);
		//webSettings.setJavaScriptCanOpenWindowsAutomatically(true);// js和android交互
		// 启用javascript

		webSettings.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点	
		//webSettings.setNeedInitialFocus(true);  
		webSettings.setUseWideViewPort(true);// 设置webview自适应屏幕大小
		webSettings.setAllowFileAccess(true);  //设置可以访问文件 
		webSettings.setAllowContentAccess(true);
		// 是否允许通过file url加载的Javascript读取本地文件，默认值 false
		webSettings.setAllowFileAccessFromFileURLs(true);
		// 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
		webSettings.setAllowUniversalAccessFromFileURLs(true);
		   /**
         * 用WebView显示图片，可使用这个参数 设置网页布局类型：
         * 1、LayoutAlgorithm.NARROW_COLUMNS ：适应内容大小
         * 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
         */

		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);// 设置，可能的话使所有列的宽度不超过屏幕宽度
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//        	webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
//        } else {
//        	webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
//        }

//		  if(Build.VERSION.SDK_INT >= 19) {
//			  webSettings.setLoadsImagesAutomatically(true);
//		    } else {
//		    	webSettings.setLoadsImagesAutomatically(false);
//		    }
		//webSettings.setLoadsImagesAutomatically(true);
		webSettings.setBlockNetworkImage(true);
		webSettings.setSavePassword(true);
		webSettings.setSaveFormData(true);
		webSettings.setLightTouchEnabled(true);
		webSettings.setPluginState(PluginState.ON);
		webSettings.setRenderPriority(RenderPriority.HIGH);
		webSettings.setDatabaseEnabled(true);
		// 设置初始缩放百分比
		// 0表示依赖于setUseWideViewPort和setLoadWithOverviewMode
		// 100表示不缩放


		    webSettings.setAppCacheEnabled(true); // 设置H5的缓存打开,默认关闭
	        String cacheDirPath = getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME;
	        //String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
	        Log.i("TAG", "cacheDirPath="+cacheDirPath);
	        //设置数据库缓存路径
	        webSettings.setDatabasePath(cacheDirPath);
	        //设置  Application Caches 缓存目录
	        webSettings.setAppCachePath(cacheDirPath);
	        //开启 Application Caches 功能

			//webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
			//webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
			webSettings.setCacheMode(webSettings.LOAD_NO_CACHE);// 不使用缓存
			webSettings.setAppCacheMaxSize(1024 * 1024 * 10);
		// 启用地理定位
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			    // 用户是否需要通过手势播放媒体(不会自动播放)，默认值 true
				webSettings.setMediaPlaybackRequiresUserGesture(false);
			}


//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//			webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//		}
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
		    // chromium, enable hardware acceleration
			webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		} else {
		    // older android version, disable hardware acceleration
			webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		}


	    if(Build.VERSION.SDK_INT >=19) {
	    	webSettings.setLoadsImagesAutomatically(true);
	    } else {
	    	webSettings.setLoadsImagesAutomatically(false);
	    }

       webSettings.setDefaultFontSize(12);
       //webSettings.setTextSize(WebSettings.TextSize.NORMAL);//NORMAL为100%
       webSettings.setTextSize(WebSettings.TextSize.SMALLEST);
       webSettings.setTextZoom(100);
	    webview.setInitialScale(100);
    	webview.requestFocus();
    	webview.setFocusable(true);//获取焦点
    	webview.requestFocusFromTouch();
        webview.setScrollBarStyle(webview.SCROLLBARS_INSIDE_OVERLAY);

        //setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);//滚动条在WebView内侧显示
       // setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY)//滚动条在WebView外侧显示

	    webview.setHorizontalScrollBarEnabled(false);//设置水平滚动条，true表示允许使用
	    webview.setVerticalScrollBarEnabled(true);//设置竖直滚动条  ，false表示禁止使用
	    webview.setOverScrollMode(webview.OVER_SCROLL_NEVER);
	   // webview.setBackgroundColor(Color.rgb(255, 0, 0));
	    webview.setBackgroundResource(R.mipmap.bg);
	    webview.setBackgroundColor(Color.argb(0, 0, 0, 0));
	    //webSettings.setUserAgentString("Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; zh-tw) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16");
	  // webSettings.setUserAgentString("Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A456 MicroMessenger/6.3.27 NetType/WIFI Language/zh_CN");

	    webSettings.setSupportZoom(true);// 关闭zoom按钮
		webSettings.setBuiltInZoomControls(true);// 关闭zoom
		webSettings.setDisplayZoomControls(false);
		webSettings.setLoadWithOverviewMode(true);// 设置webview自适应屏幕大小
		//webSettings.setDefaultZoom(ZoomDensity.CLOSE);// 默认缩放模式
	   // webview.setBackgroundResource(R.color.black);



		//启用地理定位
		webSettings.setGeolocationEnabled(true);
		webSettings.setDomStorageEnabled(true);
		//设置定位的数据库路径     
	    String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
		webSettings.setGeolocationDatabasePath(dir);


		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP) {
			webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
		}
		webview.addJavascriptInterface(new JSBridge(MainActivity.this), "android");
		//webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
		//启用数据库    

		//webview.clearCache(true);
		if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT){
			webview.setWebContentsDebuggingEnabled(true);
		}
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
			    CookieManager.getInstance().setAcceptThirdPartyCookies(webview,true);
		}
//		webview.setWebContentsDebuggingEnabled(true);
		//下面是解决跨域问题，主要是解决GPS定位有些手机不好用问题。
		try {
		    if (Build.VERSION.SDK_INT >= 16) {
		        Class<?> clazz = webview.getSettings().getClass();
		        Method method = clazz.getMethod(
		                "setAllowUniversalAccessFromFileURLs", boolean.class);//利用反射机制去修改设置对象
		        if (method != null) {
		            method.invoke(webview.getSettings(), true);//修改设置
		        }
		    }
		} catch (IllegalArgumentException e) {
		    e.printStackTrace();
		} catch (NoSuchMethodException e) {
		    e.printStackTrace();
		} catch (IllegalAccessException e) {
		    e.printStackTrace();
		} catch (InvocationTargetException e) {
		    e.printStackTrace();
		}
		//以上是定位问题。
		Intent intent1 = getIntent();
		String url = intent1.getStringExtra("url");

		if(intent1 != null){
			//获取intent中的参数

			 if(url==null){
				 //webview.loadUrl("http://m45n32437.qicp.vip:15299/mobile/login/index");
				 //Toast.makeText(getApplication(), "这里走默认页面", Toast.LENGTH_LONG).show();
					//webview.loadUrl("http://172.30.9.96");
				//String host=FileUtils.readFile(MainActivity.this,"sdcard/host.txt");
				String host="http://www.17meile.com/login.php";
					webview.loadUrl(host);
				}else{
					//Toast.makeText(getApplication(), "这里走消息传递参数页面", Toast.LENGTH_LONG).show();
					webview.loadUrl(url);
				}
		}

//		  String cookiea = sharedPreferences.getString(url, "");
//	        //测试可用
//
//	        String cookie = "这里为关键cookie串 用户名 权限 等信息; domain=通过抓包工具得到; expires=Sat, 03-Aug-2019 14:01:48 GMT; path=/";
//	        //同步cookie 到 url 中
//	        if (cookiea != null) {
//	            syncCookie(url, cookiea);
//	        }
		//webview.loadUrl("http://17reader.1752bar.com/");
		//webview.loadUrl("http://172.30.9.96");
		//webview.loadUrl("http://www.yiqimedia.com");





		webview.setWebViewClient(new WebViewClient() {
			// 覆盖shouldOverrideUrlLoading 方法


			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {

				// TODO Auto-generated method stub
				// 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器

		     	Log.d("","shouldOverrideUrlLoading->"+url);

		     	//gif|jpg|jpeg|png|xls|xlsx|doc|docx|ppt|pptx|mp4|rar|zip|pdf
		     	url=url.toLowerCase();

            	if(url.endsWith(".apk")
            			||url.endsWith(".gif")
            			||url.endsWith(".jpg")
            			||url.endsWith(".jpeg")
            			||url.endsWith(".png")
            			||url.endsWith(".xls")
            			||url.endsWith(".xlsx")
            			||url.endsWith(".doc")
            			||url.endsWith(".docx")
            			||url.endsWith(".ppt")
            			||url.endsWith(".pptx")
            			||url.endsWith(".mp4")
            			||url.endsWith(".rar")
            			||url.endsWith(".zip")
            			||url.endsWith(".pdf")){

            		Toast.makeText(getApplication(), url, Toast.LENGTH_LONG).show();
//            		Uri uri = Uri.parse(url);
//            		Intent viewIntent = new Intent(Intent.ACTION_VIEW,uri);
//            		MainActivity.this.startActivity(viewIntent);
//                    Log.e("HEHE","onDownloadStart被调用：下载链接：" + url);
            		DownLoadThread downloadThread = new DownLoadThread(url);
            		downloadThread.addProgressListener(MainActivity.this);
    		        new Thread(downloadThread).start();
            		return true;
            	}else if(url.trim().startsWith("tel")){//特殊情况tel，调用系统的拨号软件拨号【<a href="tel:1111111111">1111111111</a>】
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setData(Uri.parse(url));
                        MainActivity.this.startActivity(i);


            	}else{

					//重点写入cookie
					HashMap<String, String> map = new HashMap<>();
					map.put("Referer", view.getUrl());
					view.loadUrl(url, map);
            	}

				return true;
			}
			@Override
			public void onPageFinished(WebView webView, String url)
			{
				webView.getSettings().setBlockNetworkImage(false);

				  if(!webView.getSettings().getLoadsImagesAutomatically())
				  {
				        webView.getSettings().setLoadsImagesAutomatically(true);
				  }


				  progressBar.setVisibility(View.GONE);

				//获取登陆后的cookie,看是否写入
				CookieManager cookieManager = CookieManager.getInstance();
				String CookieStr = cookieManager.getCookie(url);
//				CookieManager cookieManager = CookieManager.getInstance();
//				String cookie = cookieManager.getCookie(url);
//				String lastUser = cookie.substring(cookie.indexOf("UsUser"), cookie.length());
//				editor.putString(url, lastUser);
//				editor.commit();

				  super.onPageFinished(webView, url);
			}

		    @Override
	        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
	            progressBar.setVisibility(View.VISIBLE);
	            progressBar.setProgress(0);
	        }


			@Override
			public void onLoadResource(WebView view, String url) {
				super.onLoadResource(view, url);
			}


			@Override
			public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				// 断网或者网络连接超时
				if (errorCode == ERROR_HOST_LOOKUP
						|| errorCode == ERROR_CONNECT
						|| errorCode == ERROR_TIMEOUT) {
					view.loadUrl("about:blank"); // 避免出现默认的错误界面
					String mErrorUrl = "file:///android_asset/404.html";
					//view.loadUrl("file:///android_asset/404.html");
					view.loadUrl(mErrorUrl);

				}
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){

			       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			    	webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
			       }
				   	handler.proceed();  // 接受所有网站的证书
		            super.onReceivedSslError(view, handler, error);


			}


			@Override
			public void onScaleChanged(WebView view, float oldScale, float newScale) {
				// TODO Auto-generated method stub
				super.onScaleChanged(view, oldScale, newScale);
				Log.i("TAG", "onScaleChanged");
			}




		});



		webview.setWebChromeClient(new WebChromeClient() {

			@Override
		      public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
		        AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
		        b.setTitle("提示");
		        b.setMessage(message);
		        b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
		          @Override
		          public void onClick(DialogInterface dialog, int which) {
		            result.confirm();
		          }
		        });
		        b.setCancelable(false);
		        b.create().show();
		        return true;
		      }


			 @Override
			  public void onReceivedIcon(WebView view, Bitmap icon) {
			     super.onReceivedIcon(view, icon);

			}

			   //定位
			    public void onGeolocationPermissionsHidePrompt() {
			        super.onGeolocationPermissionsHidePrompt();
			    }
			 @Override
		        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
		            callback.invoke(origin, true, false);
		            super.onGeolocationPermissionsShowPrompt(origin, callback);
		        }




			 @Override
			   public void onProgressChanged(WebView view, int newProgress) {
//               Log.d("jiejie", "ProgressChanged++  " + newProgress);
               if(newProgress ==100){
                   progressBar.setVisibility(View.GONE);
                   //progressBar.setProgress(newProgress);
               }else {
                   progressBar.setVisibility(View.VISIBLE);
                   progressBar.setProgress(newProgress);//设置加载进度
               }
//               //super.onProgressChanged(view, newProgress);
			    super.onProgressChanged(view, newProgress);
			   }


			// For Android < 3.0
	            public void openFileChooser(ValueCallback<Uri> valueCallback) {
	                uploadMessage = valueCallback;
	                Log.e("upload","android upload for android >3.0");
	                openImageChooserActivity();
	            }

	            // For Android  >= 3.0
	            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
	                uploadMessage = valueCallback;
	                Log.e("upload","android upload for android >=3.0");
	                openImageChooserActivity();
	            }

	            //For Android  >= 4.1
	            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
	                uploadMessage = valueCallback;
	                Log.e("upload","android upload for android >=4.1");
	                openImageChooserActivity();
	            }

//	            // For Android >= 5.0
//	            @Override
//	            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
//	                uploadMessageAboveL = filePathCallback;
//	                Log.e("upload","android upload for android >=5.0");
//	               // openImageChooserActivity();
//					openFileChooseProcess5(filePathCallback,fileChooserParams);
//	                return true;
//	            }

			// For Android  >= 5.0
			@Override
			public boolean onShowFileChooser(WebView webView,
											 ValueCallback<Uri[]> filePathCallback,
											 WebChromeClient.FileChooserParams fileChooserParams) {
				openFileChooseProcess5(filePathCallback,fileChooserParams);
				return true;
			}

        });



		webview.setDownloadListener(new DownloadListener() {
		    @Override
		    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
		        Uri uri = Uri.parse(url);
		        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		        MainActivity.this.startActivity(intent);
// 
//		        Log.e("HEHE","onDownloadStart被调用：下载链接：" + url);
//		        new Thread(new DownLoadThread(url)).start();


		    }
		});




		// 点击后退按钮,让WebView后退一页(也可以覆写Activity的onKeyDown方法)
		webview.setOnKeyListener(new View.OnKeyListener() {
			@Override

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {

					if (keyCode == KeyEvent.KEYCODE_BACK) {
						if (webview.canGoBack()) {
							String title=webview.getTitle();
							//Toast.makeText(getApplication(), title+title.equals("首页"), Toast.LENGTH_LONG).show();
							//webview.getOriginalUrl()
							if(title.equals("首页")){

								if((System.currentTimeMillis() - mkeyTime) > 2000){
									mkeyTime = System.currentTimeMillis();
									Toast.makeText(getApplication(), "在点按一次退出", Toast.LENGTH_LONG).show();
									return false;
								}else{
									finish();
						   			System.exit(0);// 退出程序
						   			return true;
						   		}

							}else{
								webview.goBack();

								//Toast.makeText(getApplication(), " 返回上一页面", Toast.LENGTH_SHORT).show();
							}

							return true;
						} else {


							if((System.currentTimeMillis() - mkeyTime) > 2000){
								mkeyTime = System.currentTimeMillis();
								Toast.makeText(getApplication(), "在点按一次退出", Toast.LENGTH_LONG).show();
								return false;
							}else{
								finish();
					   			System.exit(0);// 退出程序
					   			return true;
					   		}
						}
					}
				}
				return true;//return true,截断消息， return false 底层还会进行处理，默认会关闭aa

			}



		});




	}

	private void openFileChooseProcess5(ValueCallback<Uri[]> filePathCallback,WebChromeClient.FileChooserParams fileChooserParams) {
		uploadMessageAboveL = filePathCallback;
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		if (fileChooserParams != null && fileChooserParams.getMode() == WebChromeClient.FileChooserParams.MODE_OPEN_MULTIPLE) {
			//关键在这


			intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

			//intent.putExtra("crop", "true");// 出现裁剪窗口
		}
		startActivityForResult(Intent.createChooser(intent, "文件选择"), 2);
	}

	private void openImageChooserActivity() {
		//ACTION_OPEN_DOCUMENT
		//ACTION_GET_CONTENT
		//
		//
		//
		//
		//Log.e("openImageChooserActivity","选择文件");
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);

        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "文件选择"), 2);
    }



	@Override
	protected void onResume() {
		super.onResume();

//		 wakeLock = ((PowerManager) getSystemService(POWER_SERVICE))
//					.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
//							| PowerManager.ON_AFTER_RELEASE, "TAG");
//	     	wakeLock.acquire();
//			webview.reload();
		 int mResultCode = Activity.RESULT_CANCELED;
		// 取消选择时需要回调onReceiveValue，否则网页会挂住，不会再响应点击事件
		if (mResultCode == Activity.RESULT_CANCELED) {

		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		webview.onResume();
		webview.resumeTimers();
//		if (wakeLock != null) {
//			wakeLock.release();
//		}

	}
	@Override
	protected void onStop() {

	    super.onStop();
	   // webview.reload();
	}
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1){
	        getResources();
        }//非默认值
        if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) {
            //现在是横屏如果要做竖屏判断则修改条件newConfig.orientation==Configuration.ORIENTATION_PORTRAIT
               // Nothing need to be done here

            } else {

               // Nothing need to be done here

            }

    }


	@Override
	public Resources getResources() {
	     Resources res = super.getResources();
//	     Configuration config = res.getConfiguration();
//	     config.fontScale = 1;

	     if (res.getConfiguration().fontScale != 1) {//非默认值
	        Configuration newConfig = new Configuration();
	        //newConfig.setToDefaults();//设置默认
	        newConfig.fontScale=1.0f;
	        res.updateConfiguration(newConfig, res.getDisplayMetrics());
	     }
	     return res;
	}




    @Override
    public void onBackPressed() {
        // super.onBackPressed();
    }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Check if the key event was the Back button and if there's history
		//final WebView webview = (WebView) findViewById(R.id.webView1);
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
			// 返回键退回
			//webview.goBack();
			return true;
		}
		// If it wasn't the Back key or there's no web page history, bubble up
		// to the default
		// system behavior (probably exit the activity)
		return super.onKeyDown(keyCode, event);
	}



//    private void syncCookie(String url, String cookie) {
//        try {
//            createInstance(this);//创建一个cookie管理器
//            CookieManager cookieManager = CookieManager.getInstance();
//            cookieManager.setAcceptCookie(true);
//            cookieManager.removeSessionCookie();// 移除以前的cookie
//            cookieManager.removeAllCookie();
//            StringBuilder sbCookie = new StringBuilder();//创建一个拼接cookie的容器,为什么这么拼接，大家查阅一下http头Cookie的结构
//            sbCookie.append(cookie);
//            //这里的两个key很重要，如果不知道是什么可以抓包得到
//            sbCookie.append(String.format(";domain=%s", "."));
//            sbCookie.append(String.format(";path=%s", "/"));
//            String cookieValue = sbCookie.toString();
//            cookieManager.setCookie(url, cookieValue);//为url设置cookie
//            getInstance().sync();//同步cookie
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    //销毁Webview
    @Override
    protected void onDestroy() {
        if (webview != null) {
        	webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
        	webview.clearHistory();

            ((ViewGroup) webview.getParent()).removeView(webview);
            webview.destroy();
            webview = null;
        }

        //LocationUtils.getInstance(this).removeLocationUpdatesListener();

        super.onDestroy();
    }


    //回调地址
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode)
        {
		case 1:

			if(resultCode == RESULT_OK)
			{
				Bundle bundle = data.getExtras();
		        String scanResult = bundle.getString("result");
		        webview.loadUrl("javascript:QrcodeText('"+scanResult+"');");
				//显示扫描到的内容
				Toast.makeText(this, "二维码内容:" + scanResult, Toast.LENGTH_SHORT).show();
			}
			else
			{
				Toast.makeText(this, "用户取消操作", Toast.LENGTH_SHORT).show();
			}
			break;
		case 2:

			if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }



			break;
		case 3:
			if(resultCode == RESULT_OK)
			{

				Toast.makeText(this, "用户选择图片操作", Toast.LENGTH_SHORT).show();
			}

			break;
		case 4:
			if(resultCode == RESULT_OK)
			{


			}


			break;
		case 5:
			if(resultCode == RESULT_OK)
			{



			}



			break;
		 default:
             break;
		}







	}

	//选中图片并传给js

    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != 2 || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {

			if (intent != null) {
				String dataString = intent.getDataString();
				ClipData clipData = intent.getClipData();
				if (clipData != null) {
					results = new Uri[clipData.getItemCount()];
					for (int i = 0; i < clipData.getItemCount(); i++) {
						ClipData.Item item = clipData.getItemAt(i);
						results[i] = item.getUri();
					}
				}
				if (dataString != null) {
					results = new Uri[]{Uri.parse(dataString)};
				}
			}


        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }




	public void Screen_Cut(int flag) {
		if(flag==1){
			    Toast.makeText(MainActivity.this, "禁止截屏", Toast.LENGTH_SHORT).show();
			    this.runOnUiThread(new Runnable(){

					@Override
					public void run() {
						//Toast.makeText(MainActivity.this, "禁止截屏", Toast.LENGTH_SHORT).show();
						// TODO 自动生成的方法存根
						MainActivity.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
						MainActivity.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

					}

			    });

		}else{
			  Toast.makeText(MainActivity.this, "允许截屏", Toast.LENGTH_SHORT).show();
			    this.runOnUiThread(new Runnable(){

					@Override
					public void run() {
						//Toast.makeText(MainActivity.this, "禁止截屏", Toast.LENGTH_SHORT).show();
						// TODO 自动生成的方法存根
						  MainActivity.this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);

					}

			    });
	}

	}




class JSBridge{


	@SuppressWarnings("unused")
    private BluetoothDevice remoteDevice=null;

    @SuppressWarnings("unused")
	private String provider;

    String OUT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tesseract";


  //WebView webview = (WebView) findViewById(R.id.webView1);
   Context mContext;
   public JSBridge(Context c) {
       mContext = c;
   }
	@JavascriptInterface
	public void Permission() {
		//用户权限
		 if (Build.VERSION.SDK_INT >= 23) {//6.0才用动态权限
			 	Toast.makeText(mContext,"等待打印处方", Toast.LENGTH_SHORT).show();
	        }else{
	        	Toast.makeText(mContext,"等待打印处方", Toast.LENGTH_SHORT).show();

	        }
	}

	@JavascriptInterface
	public void doprint() {

		//打印网页
		//Toast.makeText(mContext,"等待打印处方", Toast.LENGTH_SHORT).show();

		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				final WebView webview = findViewById(R.id.webView1);
				// Get a PrintManager instance
				PrintManager printManager =(PrintManager) mContext.getSystemService(PRINT_SERVICE);
				// Get a print adapter instance
				PrintDocumentAdapter printAdapter = webview.createPrintDocumentAdapter();
				// Create a print job with name and adapter instance
				String jobName = getString(R.string.app_name)+" Document";
				PrintJob printJob = printManager.print(jobName, printAdapter,new PrintAttributes.Builder().build());

				//Toast.makeText(mContext,"等待打印", Toast.LENGTH_SHORT).show();
				// Save the job object for later status checking
				//mPrintJobs.add(printJob);

				}

		});


	}

	   @JavascriptInterface
	   public void wifi_list(String message) {

	        String wserviceName = Context.WIFI_SERVICE;
	        WifiManager wm = (WifiManager) getSystemService(wserviceName);

	        WifiInfo info = wm.getConnectionInfo();
	        int strength = info.getRssi();
	        int speed = info.getLinkSpeed();
	        String units = WifiInfo.LINK_SPEED_UNITS;
	        String ssid = info.getSSID();



	        List<android.net.wifi.ScanResult> results = wm.getScanResults();
	        String otherwifi = "The existing network is: \n\n";

	        for (android.net.wifi.ScanResult result : results) {
	            otherwifi += result.SSID  + ":" + result.level + "\n";
	        }
	       Log.d("TAG", "Js Invoker Native Function");
	       Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
	   }


   @JavascriptInterface
   public void toastMessage(String message) {
       Log.d("TAG", "Js Invoker Native Function");
       Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
   }
   @JavascriptInterface
   public void exit() {


	   finish();
       System.exit(0);
   }
   @JavascriptInterface
   public void setAlarm(String message, int hour, int minutes) {
	   //设置闹铃
       ArrayList<Integer> testDays = new ArrayList<>();
       testDays.add(Calendar.MONDAY);//周1
       testDays.add(Calendar.TUESDAY);//周2
       testDays.add(Calendar.WEDNESDAY);//周3
       testDays.add(Calendar.THURSDAY);//周4
       testDays.add(Calendar.FRIDAY);//周5
       testDays.add(Calendar.SATURDAY);//周6
       testDays.add(Calendar.SUNDAY);//周7

       //String packageName = getApplication().getPackageName();
     //  Uri ringtoneUri = Uri.parse("android.resource://" + packageName + "/" + resId);
       Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
       //action为AlarmClock.ACTION_SET_ALARM
       Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM)
               //闹钟的小时
               .putExtra(AlarmClock.EXTRA_HOUR, hour)
               //闹钟的分钟
               .putExtra(AlarmClock.EXTRA_MINUTES, minutes)
               //响铃时提示的信息
               .putExtra(AlarmClock.EXTRA_MESSAGE, message)
               //用于指定该闹铃触发时是否振动
               .putExtra(AlarmClock.EXTRA_VIBRATE, true)
               //一个 content: URI，用于指定闹铃使用的铃声，也可指定 VALUE_RINGTONE_SILENT 以不使用铃声。
               //如需使用默认铃声，则无需指定此 extra。
               .putExtra(AlarmClock.EXTRA_RINGTONE, ringtoneUri)
               //一个 ArrayList，其中包括应重复触发该闹铃的每个周日。
               // 每一天都必须使用 Calendar 类中的某个整型值（如 MONDAY）进行声明。
               //对于一次性闹铃，无需指定此 extra
               .putExtra(AlarmClock.EXTRA_DAYS, testDays)
               //如果为true，则调用startActivity()不会进入手机的闹钟设置界面
               .putExtra(AlarmClock.EXTRA_SKIP_UI, false);
       if (intent.resolveActivity(getPackageManager()) != null) {
    	   mContext.startActivity(intent);
       }
   }
   @JavascriptInterface
   public void startTimer(String message, int seconds) {
	   //倒计时
	   //action为AlarmClock.ACTION_SET_TIMER
	          Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER)
	                  .putExtra(AlarmClock.EXTRA_MESSAGE, message)
	                  //倒计总时长，以秒为单位
	                  .putExtra(AlarmClock.EXTRA_LENGTH, seconds)
	                  //是否要进入系统的倒计时设置界面
	                  .putExtra(AlarmClock.EXTRA_SKIP_UI, false);
	          if (intent.resolveActivity(getPackageManager()) != null) {
	        	  mContext.startActivity(intent);
	          }
	      }
   @JavascriptInterface
   public void addCalendarEvent(String title,String desc, String location) {
	   //增加日志日程
       Calendar beginTime = Calendar.getInstance();
      // beginTime.add(Calendar.DAY_OF_MONTH,1);
       beginTime.set(2019, 1, 31, 8, 45, 30);

       Calendar endTime = Calendar.getInstance();
       //endTime.add(Calendar.DAY_OF_MONTH,6);
       endTime.set(2019, 1, 31, 8, 50, 30);
       //CalendarContract.CONTENT_URI
      // CalendarContract.Events.HAS_ALARM, 1
       //action为Intent.ACTION_INSERT
       Intent intent = new Intent(Intent.ACTION_INSERT)
               .setData(CalendarContract.Events.CONTENT_URI)
               //事件的开始时间（从新纪年开始计算的毫秒数）。
               .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime)
               //事件的结束时间（从新纪年开始计算的毫秒数）。
               .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime)
               //指定此事件是否为全天事件。
               .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY,true)
               //事件地点。Events.DURATION, "P1800S"
               .putExtra(CalendarContract.Events.EVENT_LOCATION, location)
               //事件标题。
               .putExtra(CalendarContract.Events.TITLE, title)
               //事件说明
               .putExtra(CalendarContract.Events.DESCRIPTION,desc)
               .putExtra(CalendarContract.Events.DURATION, "P1800S")
               .putExtra(CalendarContract.Events.RRULE, "FREQ=DAILY;INTERVAL=3")
               .putExtra(CalendarContract.Events.EVENT_COLOR, Color.RED);
       Toast.makeText(mContext, "插入事件成功!!!"+Color.RED, Toast.LENGTH_SHORT).show();
       if (intent.resolveActivity(getPackageManager()) != null) {
    	   mContext.startActivity(intent);
       }
   }

   @JavascriptInterface
   public void web_loadData(String Html) {
 	   webview.loadDataWithBaseURL(null,Html, "text/html", "utf-8",null);
   }
   @JavascriptInterface
   public void vibrator() {
  		Vibrator vibrator =(Vibrator) mContext.getSystemService(Service.VIBRATOR_SERVICE);
		long[] patter = {1000, 1000, 2000, 50};
		vibrator.vibrate(patter, 0);
   }


   @JavascriptInterface
   public void lightopen() {
   	Camera camera = null;
		//异常处理一定要加，否则Camera打开失败的话程序会崩溃
       try {
           Log.d("smile","camera打开");
           camera = Camera.open();
       } catch (Exception e) {
           Log.d("smile","Camera打开有问题");
           Toast.makeText(mContext, "Camera被占用，请先关闭", Toast.LENGTH_SHORT).show();
       }

       if(camera != null)
       {
           //打开闪光灯
           camera.startPreview();
           Camera.Parameters parameter = camera.getParameters();
           parameter.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
           camera.setParameters(parameter);
           Log.d("smile","闪光灯打开");


       }



   }

   @JavascriptInterface
   public void lightclose() {
   	Camera camera = null;
		//异常处理一定要加，否则Camera打开失败的话程序会崩溃
       try {
           Log.d("smile","camera打开");
           camera = Camera.open();
       } catch (Exception e) {
           Log.d("smile","Camera打开有问题");
           Toast.makeText(mContext, "Camera被占用，请先关闭", Toast.LENGTH_SHORT).show();
       }
   	 if (camera != null)
        {
            //关闭闪光灯
            Log.d("smile", "closeCamera()");
            camera.getParameters().setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(camera.getParameters());
            camera.stopPreview();
            camera.release();
            camera = null;


        }
   }
	@JavascriptInterface
   public void goback() {
		 Toast.makeText(mContext, "返回", Toast.LENGTH_SHORT).show();
		webview.goBack();
	}
	@JavascriptInterface
   public void forward() {
		 Toast.makeText(mContext, "向前", Toast.LENGTH_SHORT).show();
		webview.goForward();

	}
	@JavascriptInterface
   public void stop() {
		Toast.makeText(mContext, "停止", Toast.LENGTH_SHORT).show();
		webview.stopLoading();


	}
	@JavascriptInterface
   public void refresh() {
		Toast.makeText(mContext, "刷新", Toast.LENGTH_SHORT).show();
		webview.reload();

	}


	@JavascriptInterface
   public void clearCache() {

		runOnUiThread(new Runnable() {
		    @Override
		    public void run() {
		        final WebView webview = findViewById(R.id.webView1);
				if (webview != null) {
					Toast.makeText(mContext, "开始清理缓存", Toast.LENGTH_SHORT).show();
					webview.stopLoading();
					//webview.pauseTimers();
					webview.clearCache(true);
					webview.clearHistory();
					//webview.loadUrl("about:blank");
					//webview.loadUrl("https://upload.dmxmt.com/mobile/login/");
					//webview = null;
					Toast.makeText(mContext, "成功清理缓存", Toast.LENGTH_SHORT).show();

				}
		    }
		});




	}

	@SuppressWarnings("static-access")
	@JavascriptInterface
   public void flash() {

		for (int i=1;i<=10;i++){

   		lightopen();
	    	try {
	    		Thread.currentThread().sleep(500);

	    		} catch (InterruptedException e) {
	    		e.printStackTrace();
	    		}
	    	lightclose();

		}

		lightclose();

   }
	@JavascriptInterface
	public void get(String url){

		OkHttpClient okHttpClient = new OkHttpClient();
		Request request = new Request.Builder()
		    .url(url)
		    .build();
		Call call = okHttpClient.newCall(request);
		try {
		    Response response = call.execute();
		    System.out.println(response.body().string());
		} catch (IOException e) {
		    e.printStackTrace();
		}



	}

//	@JavascriptInterface
//	public void post(String url,String json){
//		OkHttpClient okHttpClient = new OkHttpClient();
//		RequestBody body = new FormBody.Builder()
//		    .add("键", "值")
//		    .add("键", "值")
//		    .build();
//
//		Request request = new Request.Builder()
//		    .url(url)
//		    .post(body)
//		    .build();
//
//		Call call = okHttpClient.newCall(request);
//		try {
//		    Response response = call.execute();
//		    System.out.println(response.body().string());
//		} catch (IOException e) {
//		    e.printStackTrace();
//		}
//
// 
//	}
//	
	@JavascriptInterface
	public void share(String type,String text,String img) {

		Intent textIntent = new Intent(Intent.ACTION_SEND);
        textIntent.setType("text/plain");
        textIntent.putExtra(Intent.EXTRA_TEXT, "这是一段分享的文字");
         mContext.startActivity(Intent.createChooser(textIntent, "分享"));

/*
         
         String path =img;
         Intent imageIntent = new Intent(Intent.ACTION_SEND);
         imageIntent.setType("image/jpeg");
         imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
         mContext.startActivity(Intent.createChooser(imageIntent, "分享"));

 
         
         ArrayList<Uri> imageUris = new ArrayList<>();
         Uri uri1 = Uri.parse(getResourcesUri(R.drawable.dog));
         Uri uri2 = Uri.parse(getResourcesUri(R.drawable.shu_1));
         imageUris.add(uri1);
         imageUris.add(uri2);
         Intent mulIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
         mulIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
         mulIntent.setType("image/jpeg");
         mContext.startActivity(Intent.createChooser(mulIntent,"多文件分享"));


         Intent wechatIntent = new Intent(Intent.ACTION_SEND);
         wechatIntent.setPackage("com.tencent.mm");
         wechatIntent.setType("text/plain");
         wechatIntent.putExtra(Intent.EXTRA_TEXT, "分享到微信:");
         mContext.startActivity(wechatIntent);


         Intent qqIntent = new Intent(Intent.ACTION_SEND);
         qqIntent.setPackage("com.tencent.mobileqq");
         qqIntent.setType("text/plain");
         qqIntent.putExtra(Intent.EXTRA_TEXT, "分享到QQ:");
         mContext.startActivity(qqIntent);
*/



	}
	@JavascriptInterface
	public void sendsms(String phoneNumber,String message){
		//Log.w("短信开始", "*************************************************************");
		// 获取短信管理器
		android.telephony.SmsManager smsManager = android.telephony.SmsManager
				.getDefault();
		// 拆分短信内容（手机短信长度限制）
		List<String> divideContents = smsManager.divideMessage(message);
		for (String text : divideContents) {
			smsManager.sendTextMessage(phoneNumber, null, text, null,null);
		}
		//Log.w("短信结束", "*************************************************************");
	}

	@JavascriptInterface
	public void ScreenCut(int flag) {
	 if(flag==1){
		 Screen_Cut(1);
	 }else{
		 Screen_Cut(0);
	 }

	}


	@JavascriptInterface
	public void ocr(String url) {
		Toast.makeText(mContext, "OCR", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent();

		intent.putExtra("url",url);
		intent.setClass(mContext, OcrActivity.class);
		((Activity) mContext).startActivityForResult(intent,4);


	}
	//@JavascriptInterface
//	public String gps(){
////		String pot = null;
////		Location location = LocationUtils.getInstance( MainActivity.this ).showLocation();
////        if (location != null) {
////          String address = "经度：" + location.getLongitude()+ "纬度：" + location.getLatitude() ;
////          Log.d( "FLY.LocationUtils", address );
////          Toast.makeText(mContext, address, Toast.LENGTH_SHORT).show();
////          pot =  location.getLongitude()+ "," +location.getLatitude();
//
//       / }
//
//		return pot;
//	}
	@JavascriptInterface
    public void openMap(final String address) {
        Log.i("WebView", "OpenMap");
        webview.post(new Runnable() {
            @Override
            public void run() {
                String url = "";
                if (isApp("com.autonavi.minimap")) {
                    url = "amapuri://poi?sourceApplication=ewpower.com&keywords="+address;
                    Toast.makeText(mContext, "启动高德地图", Toast.LENGTH_SHORT).show();

                }else if (isApp("com.baidu.BaiduMap")) {
                    url = "baidumap://map/geocoder?src=openApiDemo&address="+address;
                    Toast.makeText(mContext, "启动百度地图", Toast.LENGTH_SHORT).show();
                    //showToast("启动百度地图");
                } else {
                    Toast.makeText(mContext, "检测到您未安装地图APP，无法开始导航，建议您安装最新版的高德地图或百度地图", Toast.LENGTH_SHORT).show();
                   // showToast("检测到您未安装地图APP，无法开始导航，建议您安装最新版的高德地图或百度地图");
                    return;
                }

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_DEFAULT);

                //将功能Scheme以URI的方式传入data
                Uri uri = Uri.parse(url);
                intent.setData(uri);

                //启动该页面即可
                mContext.startActivity(intent);
            }
        });
    }

	@JavascriptInterface
	public void Camera() {

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系统常量， 启动相机的关键
		((Activity) mContext).startActivityForResult(intent, 3); // 参数常量为自定义的request code, 在取返回结果时有用


	}
	@JavascriptInterface
	public void video() {
	//	VIDEO
	}
	@JavascriptInterface
	public void getSensorList() {


	}

	@JavascriptInterface
	public void video_play() {


	}

	@JavascriptInterface
	public String getip() {

		try {
		    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
		      NetworkInterface intf = en.nextElement();
		      for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
		        InetAddress inetAddress = enumIpAddr.nextElement();
		        if (!inetAddress.isLoopbackAddress()) {
		        return inetAddress.getHostAddress();
		      }
		    }
		  }
		  } catch (SocketException ex) {
		      Log.e("TAG", ex.toString());
		  }
		  return null;


	}


//	@JavascriptInterface
//	public String getIMEI() {
//		TelephonyManager TelephonyMgr = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
//        @SuppressLint("MissingPermission") String imei = TelephonyMgr.getDeviceId();
//        return imei;
//
//	}
	
	@JavascriptInterface
	public String getIMSI() {
		TelephonyManager TelephonyMgr = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        @SuppressLint("MissingPermission") String imsi = TelephonyMgr.getSubscriberId();
        return imsi;
	}
	// 型号
	@JavascriptInterface
	public  String mobile_model() {
        String mtype = Build.MODEL;
        return mtype;
    }
	
	//手机品牌
	@JavascriptInterface
	public  String mobile_brand() {
        String brand = Build.BRAND;
        return brand;
    }
	
	// Mac地址 
	@JavascriptInterface
	public  String get_Mac() { 
		 try {  
	            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());  
	            for (NetworkInterface nif : all) {  
	                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;  

	                byte[] macBytes = nif.getHardwareAddress();  
	                if (macBytes == null) {  
	                    return "";  
	                }  

	                StringBuilder res1 = new StringBuilder();  
	                for (byte b : macBytes) {  
	                    res1.append(String.format("%02X:",b));  
	                }  

	                if (res1.length() > 0) {  
	                    res1.deleteCharAt(res1.length() - 1);  
	                }  
	                return res1.toString();  
	            }  
	        } catch (Exception ex) {  
	        }  
	        return "02:00:00:00:00:00";  
	  } 
	
	 
		@JavascriptInterface
		public  String getHardWare() { 
			
			 return  Build.HARDWARE;
			
		}
	
		@SuppressLint("NewApi") @JavascriptInterface
		public  String getver() { 
			
			 return  Build.VERSION.RELEASE;
			
		}
		@JavascriptInterface
		public  String getcpu() { 
		
			 return Build.CPU_ABI;
			
		}
		// 手机制造商
		@JavascriptInterface
	    public String getProduct() {
	        return Build.PRODUCT;
	    }
		
		@JavascriptInterface
	    public String Contacts() {
			        
	        JSONArray Contacts = new JSONArray();
            try {
              
            	 
    			String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};
    	        Cursor cursor = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
    	                cols, null, null, null);
    	        for (int i = 0; i < cursor.getCount(); i++) {
    	            cursor.moveToPosition(i);
    	            // 取得联系人名字
    	            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
    	            int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    	            String name = cursor.getString(nameFieldColumnIndex);
    	            String number = cursor.getString(numberFieldColumnIndex);
    	            
    	            JSONObject json = new JSONObject();
    	            
    	            json.put("id", i);
    	            json.put("name", name);
                    json.put("number", number);
                    Contacts.put(json);
    	           /// Toast.makeText(mContext, name + ":" + number, Toast.LENGTH_SHORT).show();
    	           
    	        }   
       
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
    
  
	        
			return Contacts.toString();

	
		}
		@JavascriptInterface	
		public String getVersion() {
	        try {
	            PackageManager manager = mContext.getPackageManager();
	            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(),
	                    0);
	            String version = info.versionName;
	            int versioncode = info.versionCode;
	          // Toast.makeText(mContext, "当前应用版本:" + version+"\n版本号:"+versioncode, Toast.LENGTH_SHORT).show();
	            return version;
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return "";
	    }
 
		@JavascriptInterface
		public void isInstallApp(String filename){
			
			File appFile = new File(filename);
	        if (!appFile.exists()) {
	            return;
	        }
	        // 跳转到新版本应用安装页面
	        Intent intent = new Intent(Intent.ACTION_VIEW);
	        intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive");
	        mContext.startActivity(intent);
	
			
		}
		

		@JavascriptInterface
		public void popmenu() {

		    MainActivity.this.runOnUiThread(new Runnable(){

				@Override
				public void run() {
					//Toast.makeText(MainActivity.this, "禁止截屏", Toast.LENGTH_SHORT).show();
					// TODO 自动生成的方法存根
					
					// 这里的view代表popupMenu需要依附的view
					  PopupMenu popupMenu = new PopupMenu(MainActivity.this, webview);
					  // 获取布局文件
					  popupMenu.setGravity(Gravity.CENTER);
					  Menu menu = popupMenu.getMenu();
				

					menu.add(0,1,0,"苹果");
					menu.add(0,2,0,"西瓜");
					menu.add(0,3,0,"香蕉");
					menu.add(0,4,0,"草莓");
					
					
					
				  popupMenu.show();
				  
				  

				}
		    	
		    }); 	
			
			

 
			 Toast.makeText(mContext, "取消进度条" , Toast.LENGTH_SHORT).show();
 
		}		
		
		@JavascriptInterface	
		public boolean isApp(String appPackageName) {
	        PackageManager packageManager = mContext.getPackageManager();// 获取packagemanager
	        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
	        
	        Toast.makeText(mContext, "APK文件已经安装："+appPackageName, Toast.LENGTH_SHORT).show();
	        
	        if (pinfo != null) {
	            for (int i = 0; i < pinfo.size(); i++) {
	                String pn = pinfo.get(i).packageName;
	                if (appPackageName.equals(pn)) {
	                	 Toast.makeText(mContext, "APK文件没有安装："+appPackageName, Toast.LENGTH_SHORT).show();

	                    return true;
	                }
	            }
	        }
	        Toast.makeText(mContext, "APK文件没有安装："+appPackageName, Toast.LENGTH_SHORT).show();
	        return false;
		}
		
		CustomDialog dlg = null;
		@JavascriptInterface
		public void loading(int flag) {	

		  if(flag==1)
			 {
				  if(null != this.dlg){
					 return; 
				 }
				 this.dlg = new CustomDialog(mContext);
				 this.dlg.show();
				 	return;
			 }
			 else
			 {
				  if(null == this.dlg){
					return; 
				 }

				 this.dlg.dismiss();
				 this.dlg = null;
				 return;
			 }
			 
		
             
            
		}

		
		
		ProgressDialog pd = null;
		@JavascriptInterface
		public void ProgressDialog (String title,String msg,int val,int flag){
			
			synchronized ("download") {
				//我是一个进度条对话框
			//正在下载当中...
			//int v = Integer.valueOf(val).intValue();
			if(this.pd==null){
				pd=new ProgressDialog(mContext);
			}
			if(val>99){
				 this.pd.dismiss();
				 this.pd = null;
			}
			//Toast.makeText(mContext, "取消进度条" , Toast.LENGTH_SHORT).show();
			  if(flag==1){
			
			        pd.setTitle(title);//设置一个标题
			        pd.setMessage(msg);//设置消息
			        pd.setIcon(R.mipmap.ic_launcher);//设置一个图标
			        pd.setMax(100);//设置进度条的最大值
			        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				  pd.setProgress(val);//设置进度条的当前进度
			       // pd.incrementProgressBy(val);
			        pd.setCancelable(true);//这是是否可撤销/也就是这个对话框是否可以关闭
			        pd.setIndeterminate(false);//设置是否是确定值
			 		pd.show();//展示对话框
			 		
	
				 }else{
					// webview.setVisibility(View.GONE);  
					 this.pd.dismiss();
					 this.pd = null; 
					// Toast.makeText(mContext, "取消进度条" , Toast.LENGTH_SHORT).show();
						
				 }
			}
			
 
	
			
		}
		
		@JavascriptInterface
		public void idcard_unzip() {
			///mnt/sdcard/tesseract/
			 File file = new File("/mnt/sdcard/tesseract/");
	        file.mkdirs();// 创建文件夹

			
            new Thread(){  
                public void run() {  
                    //在新线程中以同名覆盖方式解压  
                    try {  
                    	UnzipFromAssets.unZip(mContext, "tessdata.zip", OUT_PATH, true);  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    //dialog.cancel();//解压完成后关闭对话框  
                }                     
            }.start();
			
		}
	
	
	@JavascriptInterface
	public void ring(int type) {
		  Uri uri =null;
        switch (type)
        {
		case 1:
			uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			break;
		case 2:
	        uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
			break;
		case 3:
	        uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
			break;	
		case 4:
			//初始化SoundPool
			SoundPool soundPool= new SoundPool(10,AudioManager.STREAM_SYSTEM,5);
			//加载deep 音频文件
			soundPool.load(mContext,R.raw.beep,1);
			//播放deep
			soundPool.play(1,1, 1, 0, 0, 1);
        }
        
        if(type<4){
	        Ringtone ring = RingtoneManager.getRingtone(mContext, uri);
	        ring.play();
        }
	}
	
	
	@JavascriptInterface
	public void qrcode() {
		
//		Intent intent = new Intent();
//		intent.setClass(mContext, CaptureActivity.class);
//		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//		((Activity) mContext).startActivityForResult(intent,1);


		Intent intent = new Intent();
		intent.setClass(mContext, CaptureActivity.class);
		//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		((Activity) mContext).startActivityForResult(intent,1);
		
	}


	@SuppressWarnings("null")
	@JavascriptInterface
	public void pos_print(String ip,String json) {
		  List<FoodsBean> foodsBean = null; 
		  Pos pos; 
        try { 
            pos = new Pos(ip, 9100, "GBK");  //第一个参数是打印机网口IP 

            //初始化打印机 
            pos.initPos(); 

            //初始化订单数据 
            initData();

            pos.bold(true); 
            pos.printTabSpace(2); 
            pos.printWordSpace(1); 
            pos.printText("**测试店铺"); 

            pos.printLocation(0); 
            pos.printTextNewLine("----------------------------------------------"); 
            pos.bold(false); 
            pos.printTextNewLine("订 单 号：1005199"); 
            pos.printTextNewLine("用 户 名：15712937281"); 
            pos.printTextNewLine("桌  号：3号桌"); 
            pos.printTextNewLine("订单状态：订单已确认"); 
            pos.printTextNewLine("订单日期：2016/2/19 12:34:53"); 
            pos.printTextNewLine("付 款 人：线下支付（服务员：宝哥）"); 
            pos.printTextNewLine("服 务 员：1001"); 
            pos.printTextNewLine("订单备注：不要辣，少盐"); 
            pos.printLine(2); 

            pos.printText("品项"); 
            pos.printLocation(20, 1); 
            pos.printText("单价"); 
            pos.printLocation(99, 1); 
            pos.printWordSpace(1); 
            pos.printText("数量"); 
            pos.printWordSpace(3); 
            pos.printText("小计"); 
            pos.printTextNewLine("----------------------------------------------"); 

		     
            for (FoodsBean foods : foodsBean) { 
              pos.printTextNewLine(foods.getName()); 
              pos.printLocation(20, 1); 
              pos.printText(foods.getPrice()); 
              pos.printLocation(99, 1); 
              pos.printWordSpace(1); 
              pos.printText(foods.getNumber()); 
              pos.printWordSpace(3); 
              pos.printText(foods.getSum()); 
            } 

            pos.printTextNewLine("----------------------------------------------"); 

            pos.printLocation(1); 
            pos.printLine(2); 
            //打印二维码 
            pos.qrCode("https://upload.dmxmt.com/mobile/login/");

            //切纸 
            pos.feedAndCut(); 

            pos.closeIOAndSocket(); 
            pos = null; 
          } catch (UnknownHostException e) { 
            e.printStackTrace(); 
          } catch (IOException e) { 
            e.printStackTrace(); 
          } 
        } 
	

	 @SuppressWarnings("unused")
	private void initData() { 
		    ArrayList<Object> foodsBean = new ArrayList<Object>(); 
		  
		    for (int i = 0; i < 4; i++) { 
		      FoodsBean fb = new FoodsBean(); 
		      fb.setName("测试菜品" + i); 
		      fb.setPrice("90.00"); 
		      fb.setNumber("1" + i); 
		      fb.setSum("10" + i + ".00"); 
		      FoodsBean.add(fb); 
		    } 
		  }


	@JavascriptInterface
	public void send_message(String icon,String url,String headtitle,String title,String text,String subtext,int num) throws IOException {
		
		Bitmap bitmap  =FileUtils.getBitmap(icon);
		
		
		 //获取NotificationManager实例
		   NotificationManager notifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
		 
		   //实例化NotificationCompat.Builde并设置相关属性
		   
		   
           //Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);  
           //Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/Basic_tone.ogg"));  
           //Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
          // Ringtone ring = RingtoneManager.getRingtone(mContext, uri);
          // if(num==1){
        //	   ring.play();
         //  }

  	        //添加通知的事件(点击跳转到指定页面SecondActivity)
  	        Intent intent = new Intent(mContext,MainActivity.class);
  	        //intent可以携带参数到指定页面的，这里省略
  	        intent.putExtra("url",url);
  	        PendingIntent pendingIntent = PendingIntent.getActivity(mContext,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
		 /* NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
	              .setSmallIcon(R.drawable.ic_launcher)
		           .setLargeIcon(bitmap)
		           .setTicker(headtitle)
		           .setContentTitle(title)
		           .setContentText(text)
			        .setSubText(subtext)
			        .setNumber(num)
			        .setAutoCancel(true)
			        .setContentIntent(pendingIntent)
		            .setWhen(System.currentTimeMillis());
		   			notifyManager.notify(num, builder.build());
		*/


		Notification notification;
		Notification.Builder builder;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			builder=new Notification.Builder(MainActivity.this,"5996773");
		}else {
			builder=new Notification.Builder(MainActivity.this);
		}
		//设置标题
		builder.setContentTitle(headtitle);
		builder.setTicker(headtitle);
		//设置内容
		builder.setContentText(text);
		builder.setSubText(subtext);
		builder.setNumber(num);
		//设置状态栏显示的图标，建议图标颜色透明
		builder.setSmallIcon(R.mipmap.ic_launcher);
		// 设置通知灯光（LIGHTS）、铃声（SOUND）、震动（VIBRATE）、（ALL 表示都设置）
		builder.setDefaults(Notification.DEFAULT_ALL);
		//灯光三个参数，颜色（argb）、亮时间（毫秒）、暗时间（毫秒）,灯光与设备有关
		builder.setLights(Color.RED, 200, 200);
		// 铃声,传入铃声的 Uri（可以本地或网上）我这没有铃声就不传了
		builder.setSound(Uri.parse("")) ;
		// 震动，传入一个 long 型数组，表示 停、震、停、震 ... （毫秒）
		builder.setVibrate(new long[]{0, 200, 200, 200, 200, 200});
		// 通知栏点击后自动消失
		builder.setAutoCancel(true);
		// 简单通知栏设置 Intent
		builder.setContentIntent(pendingIntent);
		builder.setPriority(Notification.PRIORITY_HIGH);

		//设置下拉之后显示的图片
		builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationChannel channel = new NotificationChannel("5996773", "安卓10a", NotificationManager.IMPORTANCE_DEFAULT);
			channel.enableLights(true);//是否在桌面icon右上角展示小红点
			channel.setLightColor(Color.GREEN);//小红点颜色
			channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
			notifyManager.createNotificationChannel(channel);
		}
		notification=builder.build();
		notifyManager.notify(1,notification);


		
	}


	@JavascriptInterface
	public String netinfo(){
	int netstate = NetUtils.getNetworkState(mContext);
	String getOperatorName = NetUtils.getOperatorName(mContext);
	boolean isNetConnected = NetUtils.isNetConnected(mContext);
	boolean isWifiConnected = NetUtils.isWifiConnected(mContext);
	
	JSONObject json = new JSONObject();
     try {
			json.put("netstate", netstate);
			json.put("getOperatorName", getOperatorName);
			json.put("isNetConnected", isNetConnected);
			json.put("isWifiConnected", isWifiConnected);
	} catch (JSONException e) {
		// TODO 自动生成的 catch 块
		e.printStackTrace();
	}

  
     return json.toString();
	}	
@JavascriptInterface 
public void blueble(){

}
	
@JavascriptInterface    
public void wps_open(String path){
	 
	Intent intent = new Intent();
	Bundle bundle = new Bundle();
	bundle.putString(WpsModel.OPEN_MODE, OpenMode.NORMAL); // 打开模式
	bundle.putBoolean(WpsModel.SEND_CLOSE_BROAD, true); // 关闭时是否发送广播
	bundle.putString(WpsModel.THIRD_PACKAGE, getPackageName()); // 第三方应用的包名，用于对改应用合法性的验证
	bundle.putBoolean(WpsModel.CLEAR_TRACE, true);// 清除打开记录
	// bundle.putBoolean(CLEAR_FILE, true); //关闭后删除打开文件
	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	intent.setAction(Intent.ACTION_VIEW);
	intent.setClassName(PackageName.NORMAL, ClassName.NORMAL);

	File file = new File(path);
	if (file == null || !file.exists()) {
		 Toast.makeText(mContext, "文件为空或者不存在", Toast.LENGTH_SHORT).show();

		System.out.println("文件为空或者不存在");
		return;
	}

	Uri uri = Uri.fromFile(file);
	intent.setData(uri);
	intent.putExtras(bundle);
	try {
		startActivity(intent);
	} catch (ActivityNotFoundException e) {
		Toast.makeText(mContext, "打开wps异常："+e.toString(), Toast.LENGTH_SHORT).show();
		System.out.println("打开wps异常："+e.toString());
		e.printStackTrace();
		return;
	}
	return;
 
	 
}    
@JavascriptInterface
public void hide_kbd(){
	
	 getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
             | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
             | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
             | View.SYSTEM_UI_FLAG_IMMERSIVE);
}

@JavascriptInterface
public void menu(){

//
//	  //四个参数的含义。1，group的id,2,item的id,3,是否排序，4，将要显示的内容
//    menu.add(0,1,0,"菜单一");
//    menu.add(0,2,0,"菜单二");
//    menu.add(0,3,0,"菜单三");
//    menu.add(0,4,0,"菜单四");


}
//  @JavascriptInterface
// public void AudioRecoder(){
//
//	  View recoder = findViewById(R.layout.layout_recoder_dialog);
//	  
//  }
//@JavascriptInterface
//private void sendMessage(String message) {
//    // Check that we're actually connected before trying anything
//    if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
//        Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
//        return;
//    }
//
//    // Check that there's actually something to send
//    if (message.length() > 0) {
//        // Get the message bytes and tell the BluetoothChatService to write
//        byte[] send = message.getBytes();
//        mChatService.write(send);
//    }
//}
//@JavascriptInterface
//public void login(String UserName,String channelID){
//
//	Toast.makeText(mContext, "视频登录状态", Toast.LENGTH_SHORT).show();
////	Map<String, Object> parameters = new HashMap<String, Object>();
////	//具体ParameterKey以及详细说明请请参考Api文档。
////	parameters.put(RongRTCEngine.ParameterKey.KEY_IS_SRTP_USED,true);
////	RongRTCEngine.getInstance().setVideoParameters(parameters);
////	
////	
////	Ronginit();
////	logonToServer(UserName,channelID);	
////	
////	RongRTCVideoView localSurface = RongRTCEngine.createVideoView(getApplicationContext());
////	//创建好的view传递到RongRTCEngine中。RongRTCEngine会把相应的视频加载到此视图中
////	RongRTCEngine.getInstance().setLocalVideoView(localSurface);
//	
//	
//}
//
//public void onCharacteristicRead(final BluetoothGatt gatt,
//                                    final BluetoothGattCharacteristic characteristic,
//                                    final int status) {
//
//    Log.d("TAG", "callback characteristic read status " + status
//            + " in thread " + Thread.currentThread());
//    if (status == BluetoothGatt.GATT_SUCCESS) {
//        Log.d("TAG", "read value: " + characteristic.getValue());
//    }
//
//}

}



ProgressDialog progress = null;
@Override
public void onProgress(float val) {
	// TODO 自动生成的方法存根
	synchronized ("download") {
		//我是一个进度条对话框
	//正在下载当中...
	//int v = Integer.valueOf(val).intValue();
	if(this.progress==null){
		progress=new ProgressDialog(MainActivity.this);
	}
	if(val>99){
		 this.progress.dismiss();
		 this.progress = null;
	}
	int flag = 0;
	//Toast.makeText(mContext, "取消进度条" , Toast.LENGTH_SHORT).show();
	  if(flag==1){
	
		    progress.setTitle("下载文件");//设置一个标题
		    progress.setMessage("正在下载文件");//设置消息
		    progress.setIcon(R.mipmap.ic_launcher);//设置一个图标
		    progress.setMax(100);//设置进度条的最大值
		    progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		    progress.setProgress((int) val);//设置进度条的当前进度
	       // pd.incrementProgressBy(val);
		    progress.setCancelable(true);//这是是否可撤销/也就是这个对话框是否可以关闭
		    progress.setIndeterminate(false);//设置是否是确定值
		    progress.show();//展示对话框
	 		

		 }else{
			// webview.setVisibility(View.GONE);  
			 this.progress.dismiss();
			 this.progress = null; 
			// Toast.makeText(mContext, "取消进度条" , Toast.LENGTH_SHORT).show();
				
		 }
	}
	

}


}

